#!/usr/bin/env python3
"""
Build standalone binaries for the cold_start_analyzer CLI using PyInstaller.

Usage:
    python scripts/build.py [--extra-args ...]

Run this script on each target platform to produce a native executable under dist/.
"""

from __future__ import annotations

import argparse
import os
import pathlib
import subprocess
import sys
from typing import List


def ensure_pyinstaller() -> None:
    try:
        import PyInstaller  # type: ignore  # noqa: F401
    except ModuleNotFoundError as exc:  # pragma: no cover - simple guard
        raise SystemExit(
            "PyInstaller is not installed. Install it first, e.g.:\n"
            "    python3 -m pip install pyinstaller"
        ) from exc


def build(extra_args: List[str]) -> None:
    project_root = pathlib.Path(__file__).resolve().parents[1]
    entry_file = project_root / "cold_start_analyzer" / "main.py"
    if not entry_file.exists():
        raise SystemExit(f"Entry file not found: {entry_file}")

    sep = os.pathsep

    data_args = [
        f"cold_start_analyzer/config.ini{sep}cold_start_analyzer",
        f"cold_start_analyzer/resources{sep}cold_start_analyzer/resources",
        f"cold_start_analyzer/bin/trace_streamer_binary{sep}cold_start_analyzer/bin/trace_streamer_binary",
    ]

    hidden_imports = []
    analyzers_dir = project_root / "cold_start_analyzer" / "analyzers"
    for path in analyzers_dir.glob("*.py"):
        if path.name == "__init__.py":
            continue
        module_name = f"cold_start_analyzer.analyzers.{path.stem}"
        hidden_imports.append(module_name)

    command = [
        sys.executable,
        "-m",
        "PyInstaller",
        "--name",
        "cold_start_analyzer",
        "--onefile",
        "--clean",
        "--noconfirm",
    ]

    for data in data_args:
        command.extend(["--add-data", data])

    for module in hidden_imports:
        command.extend(["--hidden-import", module])

    command.extend(extra_args)
    command.append(str(entry_file))

    print("Running:", " ".join(command))
    subprocess.run(command, cwd=project_root, check=True)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Build cold_start_analyzer binaries via PyInstaller.")
    parser.add_argument(
        "--extra",
        nargs=argparse.REMAINDER,
        help="Additional arguments passed through to PyInstaller.",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    extra = args.extra or []
    ensure_pyinstaller()
    build(extra)


if __name__ == "__main__":
    main()
